package com.zhu.common.intercaptor;

import com.zhu.common.annotation.Token;
import com.zhu.util.EmptyUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Created by DELL on 2016/1/6.
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            Method method = ((HandlerMethod) handler).getMethod();
            Token token = method.getAnnotation(Token.class);
            if(token != null){
                HttpSession session = request.getSession();

                if("POST".equals(request.getMethod()) && token.remove()){
                    if(isRepeatRequest(request, token)){
                        response.sendRedirect(request.getContextPath() + "/login");

                        return false;
                    }

                    session.removeAttribute(token.key());
                }

                if(token.save()){
                    session.setAttribute(token.key(), UUID.randomUUID().toString());
                }
            }

            return true;
        }else{
            return super.preHandle(request, response, handler);
        }
    }

    private boolean isRepeatRequest(HttpServletRequest request, Token token){
       String sessionToken = (String)request.getSession().getAttribute(token.key());
        if(EmptyUtil.isNullOrEmpty(sessionToken)){
            return true;
        }

        String requestToken = request.getParameter(token.key());
        if(EmptyUtil.isNullOrEmpty(requestToken)){
            return true;
        }

        if(!sessionToken.equals(requestToken)){
            return true;
        }

        return false;
    }
}
